package com.yanfan.iot.tdengine.config;

import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.sql.Connection;
import java.sql.DriverManager;

@Getter
@Order(3)
@Slf4j
@Component
public class TDengineTool {

    @Autowired
    private TDengineDatabaseConfig tDengineDatabaseConfig;

    /**
     * @return
     * @Method
     * @Description 根据数据库连接自动创建数据库
     * @Param null
     * @date 2022/5/24,0024 14:32
     * @author wxy
     */
    @PostConstruct
    public void createDatabase() {
        try {
            String jdbcUrl = this.tDengineDatabaseConfig.getDbUrl();
            String username = this.tDengineDatabaseConfig.getUsername();
            String password = this.tDengineDatabaseConfig.getPassword();
            jdbcUrl = jdbcUrl.substring(0, jdbcUrl.lastIndexOf('/'));
            Connection conn = DriverManager.getConnection(jdbcUrl, username, password);
            String csql = String.format(
                    "create database if not exists %s PRECISION '%s' KEEP %d DURATION %d BUFFER %d;",
                    this.tDengineDatabaseConfig.getDbName(),
                    this.tDengineDatabaseConfig.getPrecision(),
                    this.tDengineDatabaseConfig.getKeep(),
                    this.tDengineDatabaseConfig.getDuration(),
                    this.tDengineDatabaseConfig.getBuffer()
            );
            System.out.println(csql);
            conn.createStatement().execute(csql);
            conn.close();
            log.info("完成数据库创建");
        } catch (Exception e) {
            log.info("错误", e.getMessage());
            e.printStackTrace();
        }
    }
}
